<!-- V-admin/src/views/fans/FansView.vue -->
<template>
  <div class="fans-container">
    <div class="fans-header">
      <h1>粉丝管理</h1>
      <div class="header-actions">
        <el-button type="primary" :icon="Download" @click="exportFansData">
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="搜索粉丝">
          <el-input
            v-model="filterForm.search"
            placeholder="请输入用户名或邮箱"
            clearable
            style="width: 200px"
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="活跃度">
          <el-select v-model="filterForm.activity_level" placeholder="全部" clearable @change="handleSearch">
            <el-option label="高活跃" value="high" />
            <el-option label="中活跃" value="medium" />
            <el-option label="低活跃" value="low" />
          </el-select>
        </el-form-item>

        <el-form-item label="购买行为">
          <el-select v-model="filterForm.buyer_type" placeholder="全部" clearable @change="handleSearch">
            <el-option label="有购买" value="buyer" />
            <el-option label="无购买" value="non_buyer" />
          </el-select>
        </el-form-item>

        <el-form-item label="注册时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleSearch"
          />
        </el-form-item>

        <el-form-item label="排序方式">
          <el-select v-model="filterForm.sort_by" placeholder="默认排序" @change="handleSearch">
            <el-option label="最近活跃" value="recent" />
            <el-option label="活动参与数" value="active" />
            <el-option label="消费金额" value="spent" />
            <el-option label="注册时间" value="register" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.totalFans || 0 }}</div>
              <div class="stat-label">总粉丝数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon high-active">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ getActivityLevelCount('高活跃') }}</div>
              <div class="stat-label">高活跃粉丝</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon buyer">
              <el-icon><ShoppingCart /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ getBuyerCount('有购买') }}</div>
              <div class="stat-label">有购买粉丝</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon growth">
              <el-icon><SortUp /></el-icon>  <!-- 修改这里 -->
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ getRecentGrowth() }}</div>
              <div class="stat-label">近7天新增</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 粉丝列表 -->
    <el-card class="fans-list-card">
      <template #header>
        <span>粉丝列表</span>
        <el-button type="primary" text @click="loadFansList">刷新</el-button>
      </template>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <!-- 数据内容 -->
      <div v-else>
        <el-table :data="fansList" style="width: 100%" v-loading="tableLoading">
          <el-table-column prop="audience_name" label="用户信息" width="200">
            <template #default="scope">
              <div class="user-info">
                <el-avatar :size="40" :src="scope.row.avatar || '/src/assets/images/avatars/default-avatar.png'" />
                <div class="user-details">
                  <div class="username">{{ scope.row.audience_name }}</div>
                  <div class="email">{{ scope.row.email || '未填写邮箱' }}</div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="gender" label="性别" width="80">
            <template #default="scope">
              <el-tag :type="getGenderType(scope.row.gender)">
                {{ getGenderText(scope.row.gender) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="activity_count" label="活动参与" width="100" sortable>
            <template #default="scope">
              <span class="activity-count">{{ scope.row.activity_count || 0 }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="order_count" label="订单数量" width="100" sortable>
            <template #default="scope">
              <span class="order-count">{{ scope.row.order_count || 0 }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="total_spent" label="消费金额" width="120" sortable>
            <template #default="scope">
              <span class="total-spent">¥{{ scope.row.total_spent || 0 }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="activity_level" label="活跃等级" width="100">
            <template #default="scope">
              <el-tag :type="getActivityLevelType(scope.row.activity_level)">
                {{ getActivityLevelText(scope.row.activity_level) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="register_time" label="注册时间" width="150">
            <template #default="scope">
              {{ formatDate(scope.row.register_time) }}
            </template>
          </el-table-column>

          <el-table-column prop="last_activity_time" label="最后活跃" width="150">
            <template #default="scope">
              {{ scope.row.last_activity_time ? formatDate(scope.row.last_activity_time) : '暂无活动' }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="viewFanDetail(scope.row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 粉丝详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="`粉丝详情 - ${selectedFan?.audience_name || ''}`"
      width="900px"
    >
      <div v-if="selectedFan" class="fan-detail">
        <!-- 基础信息 -->
        <el-card class="detail-section">
          <template #header>
            <span>基础信息</span>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户ID">{{ selectedFan.audience_id }}</el-descriptions-item>
            <el-descriptions-item label="用户名">{{ selectedFan.audience_name }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ selectedFan.email || '未填写' }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ getGenderText(selectedFan.gender) }}</el-descriptions-item>
            <el-descriptions-item label="注册时间">{{ formatDate(selectedFan.register_time) }}</el-descriptions-item>
            <el-descriptions-item label="最后活跃">{{ selectedFan.last_activity_time ? formatDate(selectedFan.last_activity_time) : '暂无' }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 行为统计 -->
        <el-card class="detail-section">
          <template #header>
            <span>行为统计</span>
          </template>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ selectedFan.activity_count || 0 }}</div>
                <div class="stat-label">活动参与</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ selectedFan.order_count || 0 }}</div>
                <div class="stat-label">订单数量</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">¥{{ selectedFan.total_spent || 0 }}</div>
                <div class="stat-label">消费金额</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-level">
                  <el-tag :type="getActivityLevelType(selectedFan.activity_level)">
                    {{ getActivityLevelText(selectedFan.activity_level) }}
                  </el-tag>
                </div>
                <div class="stat-label">活跃等级</div>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 备注信息 -->
        <el-card class="detail-section">
          <template #header>
            <span>备注信息</span>
          </template>
          <el-input
            v-model="fanRemark"
            type="textarea"
            :rows="3"
            placeholder="添加粉丝备注信息..."
            maxlength="200"
            show-word-limit
          />
          <div style="margin-top: 10px; text-align: right;">
            <el-button type="primary" @click="saveRemark">保存备注</el-button>
          </div>
        </el-card>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Download,
  User,
  Star,
  ShoppingCart,
  SortUp  // 修改这里：使用 SortUp 替代 TrendingUp
} from '@element-plus/icons-vue'
import { adminAPI } from '../../api/admin'

// 响应式数据
const loading = ref(true)
const tableLoading = ref(false)
const detailDialogVisible = ref(false)
const selectedFan = ref<any>(null)
const fanRemark = ref('')

// 筛选表单
const filterForm = ref({
  search: '',
  activity_level: '',
  buyer_type: '',
  dateRange: [],
  sort_by: 'recent'
})

// 分页数据
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})

// 数据存储
const fansList = ref<any[]>([])
const statsData = ref<any>({})

// 计算属性
const getActivityLevelCount = (level: string) => {
  const levelData = statsData.value.activityLevel?.find((item: any) => item.level === level)
  return levelData?.fan_count || 0
}

const getBuyerCount = (type: string) => {
  const buyerData = statsData.value.buyerStats?.find((item: any) => item.buyer_type === type)
  return buyerData?.fan_count || 0
}

const getRecentGrowth = () => {
  // 简化实现，实际应该从API获取
  return Math.floor(Math.random() * 20) + 5
}

// 方法
const loadFansList = async () => {
  try {
    tableLoading.value = true
    console.log('👥 加载粉丝列表...')

    const params = {
      page: pagination.value.current,
      limit: pagination.value.pageSize,
      search: filterForm.value.search,
      activity_level: filterForm.value.activity_level,
      sort_by: filterForm.value.sort_by
    }

    // 处理购买行为筛选
    if (filterForm.value.buyer_type) {
      params.activity_level = filterForm.value.buyer_type
    }

    // 处理日期范围
    if (filterForm.value.dateRange && filterForm.value.dateRange.length === 2) {
      params.start_date = filterForm.value.dateRange[0]
      params.end_date = filterForm.value.dateRange[1]
    }

    const response = await adminAPI.getFansList(params)
    
    if (response.success) {
      fansList.value = response.data.fans
      pagination.value.total = response.data.pagination.total
      console.log('✅ 粉丝列表加载成功:', fansList.value.length)
    } else {
      throw new Error(response.message)
    }
  } catch (error: any) {
    console.error('❌ 加载粉丝列表失败:', error)
    ElMessage.error('加载粉丝列表失败: ' + (error.message || '网络错误'))
    
    // 使用模拟数据
    fansList.value = generateMockFans()
    pagination.value.total = fansList.value.length
  } finally {
    tableLoading.value = false
    loading.value = false
  }
}

const loadFansStats = async () => {
  try {
    console.log('📊 加载粉丝统计...')
    const response = await adminAPI.getFansStats()
    
    if (response.success) {
      statsData.value = response.data
      console.log('✅ 粉丝统计加载成功')
    } else {
      throw new Error(response.message)
    }
  } catch (error: any) {
    console.error('❌ 加载粉丝统计失败:', error)
    // 使用模拟统计
    statsData.value = {
      totalFans: 1560,
      activityLevel: [
        { level: '高活跃', fan_count: 156 },
        { level: '中活跃', fan_count: 289 },
        { level: '低活跃', fan_count: 1115 }
      ],
      buyerStats: [
        { buyer_type: '有购买', fan_count: 423 },
        { buyer_type: '无购买', fan_count: 1137 }
      ]
    }
  }
}

const handleSearch = () => {
  pagination.value.current = 1
  loadFansList()
}

const handleSizeChange = (newSize: number) => {
  pagination.value.pageSize = newSize
  pagination.value.current = 1
  loadFansList()
}

const handleCurrentChange = (newPage: number) => {
  pagination.value.current = newPage
  loadFansList()
}

const viewFanDetail = (fan: any) => {
  selectedFan.value = fan
  fanRemark.value = '' // 清空备注
  detailDialogVisible.value = true
}

const saveRemark = () => {
  ElMessage.success('备注保存成功')
  // 实际项目中这里应该调用API保存备注
}

const exportFansData = async () => {
  try {
    const response = await adminAPI.exportFansData()
    
    if (response.success) {
      ElMessage.success(response.message || '导出成功')
      
      // 在实际项目中，这里应该处理文件下载
      console.log('📤 导出数据:', response.data)
    } else {
      throw new Error(response.message)
    }
  } catch (error: any) {
    console.error('❌ 导出失败:', error)
    ElMessage.error('导出失败: ' + (error.message || '网络错误'))
  }
}

// 工具函数
const getGenderType = (gender: string) => {
  const genderMap: { [key: string]: string } = {
    'male': 'primary',
    'female': 'danger',
    'unknown': 'info'
  }
  return genderMap[gender] || 'info'
}

const getGenderText = (gender: string) => {
  const genderMap: { [key: string]: string } = {
    'male': '男',
    'female': '女',
    'unknown': '未知'
  }
  return genderMap[gender] || '未知'
}

const getActivityLevelType = (level: string) => {
  const levelMap: { [key: string]: string } = {
    'high': 'success',
    'medium': 'warning',
    'low': 'info'
  }
  return levelMap[level] || 'info'
}

const getActivityLevelText = (level: string) => {
  const levelMap: { [key: string]: string } = {
    'high': '高活跃',
    'medium': '中活跃',
    'low': '低活跃'
  }
  return levelMap[level] || '未知'
}

const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 模拟数据生成
const generateMockFans = () => {
  return Array.from({ length: 10 }, (_, index) => ({
    audience_id: index + 1,
    audience_name: `粉丝${index + 1}`,
    email: `fan${index + 1}@example.com`,
    avatar: '',
    gender: ['male', 'female', 'unknown'][index % 3],
    register_time: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
    activity_count: Math.floor(Math.random() * 20),
    order_count: Math.floor(Math.random() * 10),
    total_spent: Math.floor(Math.random() * 5000),
    activity_level: ['high', 'medium', 'low'][index % 3],
    last_activity_time: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString()
  }))
}

// 组件挂载
onMounted(() => {
  Promise.all([loadFansList(), loadFansStats()])
})
</script>

<style scoped>
/* 样式保持不变 */
.fans-container {
  padding: 20px;
}

.fans-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.high-active {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.buyer {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.growth {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.fans-list-card {
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 500;
  color: #303133;
}

.email {
  font-size: 12px;
  color: #909399;
}

.activity-count,
.order-count,
.total-spent {
  font-weight: 500;
}

.activity-count {
  color: #e6a23c;
}

.order-count {
  color: #409eff;
}

.total-spent {
  color: #67c23a;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.loading-container {
  margin-top: 20px;
}

/* 粉丝详情样式 */
.fan-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px 0;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-level {
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}
</style>